package com.wsjc.app.push;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.wsjc.app.push.core.PushPersist;
import com.wsjc.app.push.core.PushTask;
import com.wsjc.common.core.bean.GetSpringBeanFactory;

/**
 * 功能说明：推送模块
 */
public class App extends HttpServlet{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory.getLogger(App.class);

	public static TransferQueue<PushTask> tasks = new LinkedTransferQueue<PushTask>();

	private ThreadPoolTaskExecutor threadPool;

	public static PushPersist pushPersist;
	
	public static GetSpringBeanFactory getSpringBeanFactory;

	@Override
	public void init() throws ServletException {
		
		try {
			getSpringBeanFactory = new GetSpringBeanFactory();
			threadPool = (ThreadPoolTaskExecutor) getSpringBeanFactory.getBean("threadPool");

			pushPersist = (PushPersist) getSpringBeanFactory.getBean("pushPersist");
			pushPersist.initPushDataLogFromDB(); // 从数据库中取一次数据用来当系统启动时初始化（此处可优化）

			Thread.sleep(3000);
			startThread(); // 启动任务处理线程

			logger.info("app-push|starting...");
		} catch (Exception e) {
			logger.error("app-push|application start error:", e);
		}finally{
			//提前GC回收。
			getSpringBeanFactory=null;
		}
	}
	
	/**
	 * 优化 线程的销毁 和 开辟所浪费的资源 PS : 2核 的cpu ,最大线程数设置4 ，核心设置为2 ，缓冲队列也是4
	 */
	private void startThread() {
		logger.info("app-push|startThread...");

		for (int i = 0; i < 1; i++) {
//			for (int i = 0; i < threadPool.getMaxPoolSize(); i++) {

			threadPool.execute(new Runnable() {
				
				/** 当前执行次数 **/
			    int executeCount = 0;
				  
			    /** 默认最大执行次数 3 **/
			    int executeMaxCount = 3;
			    
				public void run() {
					try {
						while (true) {
							PushTask task = null ;
							if(executeCount == 0){
//								Thread.sleep(1500);
								Thread.sleep(10000);
								task = tasks.poll(); // 使用take方法获取过期任务,如果获取不到,就一直等待,知道获取到数据并删除
								logger.info("app-push|executeCount={}|剩余大小==>tasks.size={}:", executeCount, tasks.size());
							}
							if (task != null) {
								task.run(executeCount, executeMaxCount); // 执行更新map
							}
						}
					} catch (Exception e) {
						logger.error("app-push|task run error;", e);
					}
				}
			});

		}
	}

}
